package ai.zixing.mashibing.new_class.class03;

import java.util.Arrays;

public class Code01_BSExist {
    public static void main(String[] args) {
        int maxSize = 10;
        int maxValue = 100;
        int testTimes = 10000;
        boolean sucessed = true;
        for (int i = 0; i < testTimes; i++) {
            int[] arr = generateRandomArr(maxSize, maxValue);
            Arrays.sort(arr);
            int value = (int) (maxValue * Math.random());
            if (test(arr, value) != find(arr, value)) {
                System.out.println("出错了!!!");
                sucessed = false;
                break;
            }
        }
    }

    public static boolean find(int[] arr, int num) {
        if (arr == null || arr.length == 0) {
            return false;
        }
        int left = 0;
        int right = arr.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (arr[mid] == num) {
                return true;
            } else if (arr[mid] < num) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return false;
    }

    public static int[] generateRandomArr(int maxSize, int maxValue) {
        int arr[] = new int[(int) ((maxSize + 1) * Math.random())];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int) (maxValue * maxValue);
        }
        return arr;
    }

    public static boolean test(int[] arr, int value) {
        for (int cur : arr) {
            if (cur == value) {
                return true;
            }
        }
        return false;
    }
}
